package com.goldsign.pay.common.util.rsa;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 
 * @author xiaoxianwen
 *
 */
public class RsaEncrypt {  
    /** 
     * 字节数据转字符串专用集合 
     */  
    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',  
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };  
  
    /** 
     * 随机生成密钥对 
     */  
    public static void genKeyPair(String filePath) {  
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象  
        KeyPairGenerator keyPairGen = null;  
        try {  
            keyPairGen = KeyPairGenerator.getInstance("RSA");  
           
        } catch (NoSuchAlgorithmException e) {  
            // TODO Auto-generated catch block  
              
        }  
        // 初始化密钥对生成器，密钥大小为96-1024位  
        keyPairGen.initialize(1024,new SecureRandom());  
        // 生成一个密钥对，保存在keyPair中  
        KeyPair keyPair = keyPairGen.generateKeyPair();  
        // 得到私钥  
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
        // 得到公钥  
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
        try {  
        	BASE64Encoder encoder=new BASE64Encoder();
            // 得到公钥字符串  
            /*String publicKeyString = Base64.encode(publicKey.getEncoded());  
            // 得到私钥字符串  
            String privateKeyString = Base64.encode(privateKey.getEncoded());  
            */
            String publicKeyString = encoder.encode(publicKey.getEncoded());  
            // 得到私钥字符串  
            String privateKeyString = encoder.encode(privateKey.getEncoded());  
            
            // 将密钥对写入到文件  
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");  
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");  
            BufferedWriter pubbw = new BufferedWriter(pubfw);  
            BufferedWriter pribw = new BufferedWriter(prifw);  
            pubbw.write(publicKeyString);  
            pribw.write(privateKeyString);  
            pubbw.flush();  
            pubbw.close();  
            pubfw.close();  
            pribw.flush();  
            pribw.close();  
            prifw.close();  
        } catch (Exception e) {  
              
        }  
    }  
  
    /** 
     * 从文件中输入流中加载公钥 
     *  
     * @param in 
     *            公钥输入流 
     * @throws Exception 
     *             加载公钥时产生的异常 
     */  
    public static String loadPublicKeyByFile(String path,String fileName) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(path  
                    + "/"+fileName));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                sb.append(readLine);  
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("公钥数据流读取错误");  
        } catch (NullPointerException e) {  
            throw new Exception("公钥输入流为空");  
        }  
    }  
   
    /**
     * 公的和私的也一起load进来string
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String loadKeyByClasspath(String fileName) throws Exception {  
    	BufferedReader br=null;
        try { 
        	String file_src = RsaEncrypt.class.getResource("/keystore").toString().replace("file:/", "")+"/"+fileName;
        	System.out.println("file_src:"+file_src); 
        	InputStream resourceAsStream =  new FileInputStream(new File(file_src));
    		//RSAEncrypt.class.getClassLoader().getResourceAsStream("/"+fileName);
        	InputStreamReader inputStreamReader=new InputStreamReader(resourceAsStream);
        	
            br = new BufferedReader(inputStreamReader); 
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                sb.append(readLine);  
            }  
            br.close();  
            System.out.println("【loadKeyByClasspath取出的密钥】："+sb.toString());
            return sb.toString();
//            String str = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALXJQay78zMXWZWbdbnz5pfADnj4\r\n" + 
//            		"JfNdJoauXMMvrrh7ghy5L1gFE3WkCJe/6IfKuwDXlRdZwRVG7PK5Lbc7TesHpU0kXSzIBgIzYyLk\r\n" + 
//            		"ggjCPZsRSa6T7nXtRNMDGvGRIZn66RL5JlBm/wy9nrdG59JpBs/ShiBpXmgI4p5G2x8RAgMBAAEC\r\n" + 
//            		"gYBNxNTA1gNcFyAvHbvGmq5Ku1I1tEtgCrjBo3Rx2ENSDxyBt0Omzz0c9djrOqF6/mL0IEZbH/23\r\n" + 
//            		"YYla6ZfCLK/PJID7BC5Gg1TtGnrGzjDyLHS+KVfucphjMVyi4S/z6Ez6EjGWDiPAiDj1iNk+xFyX\r\n" + 
//            		"DuVHKVlBEU9uMdbDMoRfQQJBAOeo1+XHSa/5uGPlKXfJCThW+Y63RiZ8oct4aC/feV3okgQGRXGl\r\n" + 
//            		"44efwmZE5ShjYsWgiCYEOEwrTH2n453YKokCQQDI4uxtXndKTxp9tWxKVEhArDcwuP8eBspRlzNp\r\n" + 
//            		"dnZ0K9DCEURlfcDB4mkozdlov1XB1qlGu1qU5lclr69j545JAkEAhuM5UwIHVgAB7aixzJ2yUKvU\r\n" + 
//            		"A9WTczV+wAsMH1PwR030N4OvS81b/sx3VTUoeavlB03B+ODcJv3PPBtV3cLQgQJBAIqqSTT9fi5n\r\n" + 
//            		"CAw6DTQJlY4+0iHpsQBTA5jqW+yyfvWVwRYUwTelZEbxOFGYNjhdyp5wxIw0i0Q483LqIJE/pzEC\r\n" + 
//            		"QQCBsOHCMbKIr8CsL2rhx4dEvH9oqPK+IxnTuzrGUCsegvAE4B8j30Skaf6m/rhZi6kegbILfA4U\r\n" + 
//            		"tkIq85UR1YSB";
//            return str;
        } catch (IOException e) {  
        	e.printStackTrace();
            throw new Exception("公钥数据流读取错误");  
        } catch (NullPointerException e) {  
            throw new Exception("公钥输入流为空");  
        } finally{
//        	br.close();
        }
    }
  
    /** 
     * 从字符串中加载公钥 
     *  
     * @param publicKeyStr 
     *            公钥数据字符串 
     * @throws Exception 
     *             加载公钥时产生的异常 
     */  
    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)  
            throws Exception {  
        try {  
        	BASE64Decoder decoder=new BASE64Decoder();
        	
            byte[] buffer = decoder.decodeBuffer(publicKeyStr);  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);  
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("公钥非法");  
        } catch (NullPointerException e) {  
            throw new Exception("公钥数据为空");  
        }  
    }  
  
    /** 
     * 从文件中加载私钥 
     *  
     * @param keyFileName 
     *            私钥文件名 
     * @return 是否成功 
     * @throws Exception 
     */  
    public static String loadPrivateKeyByFile(String path,String fileName) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(path  
                    + "/"+fileName));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                sb.append(readLine);  
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("私钥数据读取错误");  
        } catch (NullPointerException e) {  
            throw new Exception("私钥输入流为空");  
        }  
    }  
  
    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)  
            throws Exception {  
    	System.out.println("【RSAPrivateKey】"+privateKeyStr);
        try {  
        	BASE64Decoder decoder=new BASE64Decoder();
            byte[] buffer = decoder.decodeBuffer(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("私钥非法");  
        } catch (NullPointerException e) {  
            throw new Exception("私钥数据为空");  
        }  
    }  
  
    /** 
     * 公钥加密过程 
     *  
     * @param publicKey 
     *            公钥 
     * @param plainTextData 
     *            明文数据 
     * @return 
     * @throws Exception 
     *             加密过程中的异常信息 
     */  
    public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)  
            throws Exception {  
        if (publicKey == null) {  
            throw new Exception("加密公钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
        	//cipher=Cipher.getInstance("RSA/ECB/NoPadding");
            //cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
            byte[] output = cipher.doFinal(plainTextData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此加密算法");  
        } catch (NoSuchPaddingException e) {  
              
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("加密公钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("明文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("明文数据已损坏");  
        }  
    }  
  
    /** 
     * 私钥加密过程 
     *  
     * @param privateKey 
     *            私钥 
     * @param plainTextData 
     *            明文数据 
     * @return 
     * @throws Exception 
     *             加密过程中的异常信息 
     */  
    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)  
            throws Exception {  
        if (privateKey == null) {  
            throw new Exception("加密私钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
        	//cipher=Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
            byte[] output = cipher.doFinal(plainTextData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此加密算法");  
        } catch (NoSuchPaddingException e) {  
              
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("加密私钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("明文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("明文数据已损坏");  
        }  
    }  
  
    /** 
     * 私钥解密过程 
     *  
     * @param privateKey 
     *            私钥 
     * @param cipherData 
     *            密文数据 
     * @return 明文 
     * @throws Exception 
     *             解密过程中的异常信息 
     */  
    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)  
            throws Exception {  
        if (privateKey == null) {  
            throw new Exception("解密私钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
           // cipher=Cipher.getInstance("RSA/ECB/NoPadding");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.DECRYPT_MODE, privateKey);  
            byte[] output = cipher.doFinal(cipherData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此解密算法");  
        } catch (NoSuchPaddingException e) {  
              
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("解密私钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("密文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("密文数据已损坏");  
        }  
    }  
  
    /** 
     * 公钥解密过程 
     *  
     * @param publicKey 
     *            公钥 
     * @param cipherData 
     *            密文数据 
     * @return 明文 
     * @throws Exception 
     *             解密过程中的异常信息 
     */  
    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)  
            throws Exception {  
        if (publicKey == null) {  
            throw new Exception("解密公钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
        	//cipher=Cipher.getInstance("RSA/ECB/NoPadding");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.DECRYPT_MODE, publicKey);  
            byte[] output = cipher.doFinal(cipherData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此解密算法");  
        } catch (NoSuchPaddingException e) {  
              
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("解密公钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("密文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("密文数据已损坏");  
        }  
    }  
  
    /** 
     * 字节数据转十六进制字符串 
     *  
     * @param data 
     *            输入数据 
     * @return 十六进制内容 
     */  
    public static String byteArrayToString(byte[] data) {  
        StringBuilder stringBuilder = new StringBuilder();  
        for (int i = 0; i < data.length; i++) {  
            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移  
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);  
            // 取出字节的低四位 作为索引得到相应的十六进制标识符  
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);  
            if (i < data.length - 1) {  
                stringBuilder.append(' ');  
            }  
        }  
        return stringBuilder.toString();  
    }  
    
    public static void main(String[] args) throws IOException {
//    	InputStream resourceAsStream = RSAEncrypt.class.getClassLoader().getResourceAsStream("resources/conf/a.txt");
//    	InputStreamReader inputStreamReader=new InputStreamReader(resourceAsStream);
//    	BufferedReader reader=new BufferedReader(inputStreamReader);
//    	String line=null;
//    	while((line=reader.readLine())!=null){
//    		SysLog.info(line);
//    	}
//    	reader.close();
    	
//    	String path="E://keyFolder";
//    	String publicFile="publicKey.keystore";
//    	String privateFile="privateKey.keystore";
//    	
    	try {
//    		genKeyPair(path);
//			String publicKey=loadPublicKeyByFile(path,publicFile);
//			String privateKey=loadPrivateKeyByFile(path,privateFile);
//			System.out.println("公"+publicKey);
//			System.out.println("私"+privateKey);
//			String param="123456";
//			byte[] bytes=param.getBytes();
//			RSAPublicKey pubKey= loadPublicKeyByStr(publicKey);
//			//System.out.println("公2"+pubKey);
//			byte[] encrypt = encrypt(pubKey, bytes);
//			System.out.println(new String(encrypt));
			
//    	String str = loadKeyByClasspath("PrivateKey.keystore");
		String file_src = RsaEncrypt.class.getResource("/keystore").toString().replace("file:/", "");
    	System.out.println(file_src);
    	System.out.println(System.getProperty("file.separator"));
    	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
	}
}  
